#include "SceneSynthesis.h"

#ifdef SceneSyn_PREPROCESSING
string conferencePath="E:/conferenceroom/conference_room5/Relationship.cng";
map<string,WallGrid> wallGridMap;
vector<CandidateType*> candidateVector;
map<string,CandidateType*> candidateMap; // tag: tag+candidate.type
map<string,vector<GGroup*>*> groupMap;// grouptype : groups
vector<Scene*> sceneVector;
Scene scene;
#endif

void ConstructCandidates( map<string,WallGrid> &gridMap,vector<CandidateType*> &candidateVector,map<string,CandidateType*> &candidateMap )
{
	candidateVector.reserve(50);

	map<string,WallGrid>::iterator it;
	for (it=gridMap.begin();it!=gridMap.end();++it)
	{
		WallGrid &grid=it->second;
		for(int i=0;i<grid.CategoryVector.size();++i)
		{
			CandidateType* can=new CandidateType;
			can->heightIndex=grid.heightIndex;
			can->widthIndex=grid.widthIndex;
			can->tag=grid.tag;
			can->groupName=grid.CategoryVector[i].tag;
			can->probability=grid.probability*grid.CategoryVector[i].probability;
			candidateVector.push_back(can);
			string tag=can->tag+can->groupName;
			candidateMap.insert(pair<string,CandidateType*>(tag,can));
		}
	}
	sort(candidateVector.begin(),candidateVector.end(),greater<CandidateType*>());
}


void GenerateNewScenes( vector<Scene*> &sceneVector,Scene *scene,vector<CandidateType*> &candidateVector, map<string,vector<GGroup*>*> &groupMap )
{
	for (int i=0;i<candidateVector.size();++i)
	//for (int i=0;i<2;++i)
	{
		CandidateType* candidate=candidateVector[i];
		if(scene->WallGridOccupancy[candidate->heightIndex][candidate->widthIndex]==1)
			continue;

		vector<GGroup*>* gVector=groupMap[candidate->groupName];

		bool flag=(*gVector)[0]->DeformGroupByWallGrid(candidate->heightIndex,candidate->widthIndex,scene);

		//if(flag && !(*gVector)[0]->isMeshesLoaded)

		if(flag)
		{
			(*gVector)[0]->ReadMeshes();
			(*gVector)[0]->ApplyTransfromation();
			(*gVector)[0]->isNewAdded=true;
			scene->groupVectors.push_back((*gVector)[0]);
		}
	}
}



#ifdef SceneSyn_PREPROCESSING
void DoSceneSynethesis()
{
	scene.ReadSceneByGroup(conferencePath);
	scene.ReadModelMesh();
	//scene.CalculateGroupDirection();
	scene.ExtractWallGridDistribution();

	ReadWallStatistics(wallGridMap,wallStatisticPath);
	ConstructCandidates(wallGridMap,candidateVector,candidateMap);

	ReadGroups(groupMap);

	GenerateNewScenes(sceneVector,&scene,candidateVector,groupMap);

	ClearAllMem();
}

void ClearAllMem()
{
	for (int i=0;i<candidateVector.size();++i)
		delete candidateVector[i];

	map<string,vector<GGroup*>*>::iterator it;
	for(it=groupMap.begin();it!=groupMap.end();++it)
	{
		vector<GGroup*>* groups=it->second;
		for(int i=0;i<groups->size();++i)
			delete (*groups)[i];
		delete groups;
	}
}

#endif
